package cn.react.com.itchenrana;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;

public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {


	private ReactRootView mReactRootView;
	private ReactInstanceManager mReactInstanceManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//setContentView(R.layout.activity_my_react);

		mReactRootView = new ReactRootView(this);
		mReactInstanceManager = ReactInstanceManager.builder()
				.setApplication(getApplication())
				.setBundleAssetName("index.android.bundle")
				.setJSMainModuleName("index.android")
				.addPackage(new MainReactPackage())
				//.setUseDeveloperSupport(BuildConfig.DEBUG)
				.setUseDeveloperSupport(true)
				.setInitialLifecycleState(LifecycleState.RESUMED)
				.build();
		// startReactApplication 方法中的 moduleName 参数必须和你在index.android.js 文件中                  // AppRegistry.registerComponent 注册的项目名称保持一致
		mReactRootView.startReactApplication(mReactInstanceManager, "myapplication", null);
		setContentView(mReactRootView);

	}

	/**
	 * By default, all onBackPress() calls should not execute the default backpress handler and should
	 * instead propagate it to the JS instance. If JS doesn't want to handle the back press itself,
	 * it shall call back into native to invoke this function which should execute the default handler
	 */
	@Override
	public void invokeDefaultOnBackPressed() {
		super.onBackPressed();
	}
	@Override
	protected void onResume() {
		super.onResume();
		if (mReactInstanceManager != null) {
			mReactInstanceManager.onHostResume(this, this);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mReactInstanceManager != null) {
			mReactInstanceManager.onHostPause();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mReactInstanceManager != null) {
			mReactInstanceManager.onHostDestroy();
		}
	}

	@Override
	public void onBackPressed() {
		if (mReactInstanceManager != null) {
			mReactInstanceManager.onBackPressed();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
			mReactInstanceManager.showDevOptionsDialog();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}
}
